import cv2
import numpy as np
import pyautogui

def capture_screen():
    """截取当前屏幕并返回 OpenCV 格式的图像"""
    screenshot = pyautogui.screenshot()
    # 将 PIL 图像对象转换为 NumPy 数组
    screenshot = np.array(screenshot)
    # 将 BGR 格式转换为 RGB 格式（可选，取决于后续处理需求）
    screenshot = cv2.cvtColor(screenshot, cv2.COLOR_BGR2RGB)
    return screenshot

def match_images(screen_image, target_image, threshold):
    """进行图像匹配并返回匹配结果"""
    # 将目标图片转换为灰度图像
    gray_target = cv2.cvtColor(target_image, cv2.COLOR_RGB2GRAY)
    # 将屏幕截图转换为灰度图像
    gray_screen = cv2.cvtColor(screen_image, cv2.COLOR_RGB2GRAY)
    
    result = cv2.matchTemplate(gray_screen, gray_target, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    
    if max_val >= threshold:
        # 获取目标图片的宽度和高度
        target_h, target_w = gray_target.shape
        # 计算匹配区域的中心位置
        center_x = max_loc[0] + target_w // 2
        center_y = max_loc[1] + target_h // 2
        return True, (center_x, center_y)
    else:
        return False, None